function [IndLists, RGB] = nucAndLDMasksToIndLists(M,L,imSize0) % M: nuclei mask, L: LD mask

L = selectByContact(L,M);

L = imresize(L,imSize0,'nearest');
M = imresize(M,imSize0,'nearest');

s = regionprops(M,'PixelIdxList','Centroid');
centroids = cat(1,s.Centroid);
hues = linspace(0,2/3,length(s));
hues = hues(randperm(length(s)));
LM = zeros(size(M)); % labels / nuclei
Hue = zeros(size(M));
cellLabels = cell(1,length(s));
for i = 1:length(s)
    LM(s(i).PixelIdxList) = i;
    Hue(s(i).PixelIdxList) = hues(i);
    cellLabels{i} = sprintf('%d',i);
end


s = regionprops(L,'PixelIdxList');

LL = zeros(size(L)); % labels / LD
maskL = false(size(L));
VM = 0.5*ones(size(Hue));
for i = 1:length(s) % iterate on LD components
    idx = s(i).PixelIdxList;
    lidx = LM(idx);
    ul = unique(lidx);
    
    nInCell = sum(lidx > 0);
    nTotal = numel(lidx);
%     if nInCell/nTotal > 0.75
%         LL(idx) = 1;
%     else
%         
%         LL(idx) = 0.25;
%     end
%     continue
    
    if nInCell/nTotal > 0.75
        ul =  ul(ul > 0);
        if numel(ul) == 1
            LL(idx) = ul;
            maskL(idx) = true;
            Hue(idx) = hues(ul);
            VM(idx) = 1;
        else
            cs = zeros(1,length(ul));
            for j = 1:length(ul)
                cs(j) = sum(lidx == ul(j));
            end
            [m1,im1] = max(cs);
            cs(im1) = 0;
            [m2,im2] = max(cs);
            if m2/m1 > 0.25
                idx1 = idx(LM(idx) == ul(im1));
                LL(idx1) = ul(im1);
                maskL(idx1) = true;
                Hue(idx1) = hues(ul(im1));
                VM(idx1) = 1;
                idx2 = idx(LM(idx) == ul(im2));
                LL(idx2) = ul(im2);
                maskL(idx2) = true;
                Hue(idx2) = hues(ul(im2));
                VM(idx2) = 1;
            else
                maskL(idx) = true;
                LL(idx) = ul(im1);
                Hue(idx) = hues(ul(im1));
                VM(idx) = 1;
            end
        end
    end
end

HSV = cat(3,cat(3,Hue,ones(size(Hue))),VM);
RGB = hsv2rgb(HSV);

for i = 1:3
    I = RGB(:,:,i);
    I(not(M | maskL)) = 0;
    RGB(:,:,i) = I;
end

RGB = insertText(RGB, centroids, cellLabels, 'FontSize', 36, 'TextColor', 'black', 'BoxColor', 'white', 'BoxOpacity', 0.5);

IndLists = cell(max(LM(:)),2);
for i = 1:max(LM(:))
    idxInLD = find(LL == i);
    idxNotInLD = find(LM == i & LL ~= i);
    IndLists{i,1} = idxInLD;
    IndLists{i,2} = idxNotInLD;
end

end